#include "main.h"

// setting parameters
int     temp_set;        // 
uint8_t temp_alert;      // 
int     temp_pid;        // 
char    temp_offset;     //
int     temp_shutdown;
int     temp_pwm;
uint8_t temp_lock;
uint8_t mode;
bool    offset_positive;
uint8_t ohm;

void eeprom_init()
{
	FLASH_CR1=0x00;
	FLASH_CR2=0x00;
	FLASH_NCR2=0xFF;
	FLASH_DUKR=0xae;
	FLASH_DUKR=0x56;
	while(!(FLASH_IAPSR&0x08));
}

void eeprom_write(uint8_t addr, uint8_t  dat)
{
	uint8_t  *p;
	p=(uint8_t *)(0x4000+addr);
	*p=dat;
	while(!(FLASH_IAPSR&0x04));
}

uint8_t eeprom_read(uint8_t  addr)
{
	uint8_t *p;
	p=(unsigned char  *)(0x4000+addr); 
	return *p; 
}

void read_parameter(void)
{
	// 读取offset
	if (eeprom_read(ADDR_OFFSET_H)==POSITIVE) {
		offset_positive = TRUE;
		temp_offset = eeprom_read(ADDR_OFFSET_L);
	}else if (eeprom_read(ADDR_OFFSET_H)==NEGETIVE) {
		offset_positive = FALSE;
		temp_offset = eeprom_read(ADDR_OFFSET_L);
	}else{
		offset_positive = TRUE;
		temp_offset = OFFSET_DEFAULT;
	}

	// 读取PID的P值
	temp_pid = eeprom_read(ADDR_PID_H)<<8;
	temp_pid += eeprom_read(ADDR_PID_L);

	temp_set = eeprom_read(ADDR_SET_H)<<8;
	temp_set += eeprom_read(ADDR_SET_L);

	// 读取temp_alert
	temp_alert = eeprom_read(ADDR_ALERT_VALUE);

	// 读取temp_pwm
	temp_pwm = eeprom_read(ADDR_PWM_VALUE);

	// 读取temp_lock
	temp_lock = eeprom_read(ADDR_LOCK_VALUE);

	// 读取电阻值
	ohm = 47;

	temp_shutdown = 0;

}

void load_default_parameter(void)
{
	temp_pid = PID_DEFAULT;
	temp_set = SET_DEFAULT;
	temp_alert = ALERT_DEFAULT;
	temp_pwm = PWM_DEFAULT;
	temp_lock = LOCK_DEFAULT;
	temp_shutdown = 0;
	save_parameter();
}

void save_parameter(void)
{
	// save offset
	if (offset_positive) {
		eeprom_write(ADDR_OFFSET_H, POSITIVE);
		eeprom_write(ADDR_OFFSET_L, temp_offset);
	}else{
		eeprom_write(ADDR_OFFSET_H, NEGETIVE);
		eeprom_write(ADDR_OFFSET_L, temp_offset);
	}

	// save pid value
	eeprom_write(ADDR_PID_H, temp_pid/256);
	eeprom_write(ADDR_PID_L, temp_pid%256);

	// save alert
	eeprom_write(ADDR_ALERT_VALUE, temp_alert);

	// save temp_pwm
	eeprom_write(ADDR_PWM_VALUE, temp_pwm);

	// save temp_lock
	eeprom_write(ADDR_LOCK_VALUE, temp_lock);

	// save ohm
	eeprom_write(ADDR_OHM_VALUE, ohm);

}

void save_set_temp(void)
{
	// save set_point
	eeprom_write(ADDR_SET_H, temp_set/256);
	eeprom_write(ADDR_SET_L, temp_set%256);
}